package servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.PaperDao;
import dao.UserDao;
import entity.PaperInfo;

public class IndexSubjectServlet extends HttpServlet {
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");

		int start = 0;
		int count = 8;
		int subject = Integer.parseInt(request.getParameter("subject"));
		request.getSession().setAttribute("subject", subject);

		try {
			start = Integer.parseInt(request.getParameter("start"));
		} catch (NumberFormatException e) {

		}

		int next = start + count;
		int pre = start - count;
		int total = new PaperDao().getTotal(subject);

		int last;
		if (0 == total % count)
			last = total - count;
		else
			last = total - total % count;
		pre = pre < 0 ? 0 : pre;
		next = next > last ? last : next;

		request.setAttribute("next", next);
		request.setAttribute("pre", pre);
		request.setAttribute("last", last);

		String userName = (String) request.getSession().getAttribute("loginFlg");
		int userId = new UserDao().search(userName).getUserId();
		List<PaperInfo> papers = new PaperDao().listRecord(start, count, userId, subject);
		request.setAttribute("papers", papers);
		request.setAttribute("subject", subject);
		
		if (subject == 1) {
			request.getRequestDispatcher("subjectOne.jsp").forward(request, response);
		} else if (subject == 4) {
			request.getRequestDispatcher("subjectFour.jsp").forward(request, response);

		}

	}

}
